package com.runtu.domain.trade.service.lock.filter;

import com.runtu.domain.trade.adapter.repository.ITradeRepository;
import com.runtu.domain.trade.model.entity.GroupBuyActivityEntity;
import com.runtu.domain.trade.model.entity.TradeLockRuleCommandEntity;
import com.runtu.domain.trade.model.entity.TradeLockRuleFilterBackEntity;
import com.runtu.domain.trade.service.lock.factory.TradeLockRuleFilterFactory;
import com.runtu.types.design.framework.link.model2.handler.ILogicHandler;
import com.runtu.types.enums.ResponseCode;
import com.runtu.types.exception.AppException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @ClassName UserTakeLimitRuleFilter
 * @Description 用户拼团限定次数的过滤
 * @date 2025/8/11 14:11
 * @Version 1.0
 */
@Slf4j
@Service
public class UserTakeLimitRuleFilter implements ILogicHandler<TradeLockRuleCommandEntity, TradeLockRuleFilterFactory.DynamicContext, TradeLockRuleFilterBackEntity> {
    @Resource
    private ITradeRepository tradeRepository;


    @Override
    public TradeLockRuleFilterBackEntity apply(TradeLockRuleCommandEntity requestParameter, TradeLockRuleFilterFactory.DynamicContext dynamicContext) throws Exception {
        log.info("交易规则过滤-用户参与次数校验{} activityId:{}", requestParameter.getUserId(), requestParameter.getActivityId());

        GroupBuyActivityEntity groupBuyActivity = dynamicContext.getGroupBuyActivity();
        /*1、查询用户拼团的次数*/
        Integer count = tradeRepository.queryOrderCountByActivityId(requestParameter.getActivityId(),requestParameter.getUserId());

        /*2、校验用户是否超出拼团限制次数*/
        if (groupBuyActivity.getTakeLimitCount() != null && count >= groupBuyActivity.getTakeLimitCount()){
            throw  new AppException(ResponseCode.E0103);
        }

        return TradeLockRuleFilterBackEntity.builder()
                .userTakeOrderCount(count)
                .build();
    }
}
